/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

/**
 *
 * @author K u Ku
 */
public class Excel {
    public static void importExcel(String pathFile){
        try {
            File file = new File(pathFile);
            Workbook wb = Workbook.getWorkbook(file);
            Sheet sheet = wb.getSheet(0);
            int rows = sheet.getRows();
            int cols = sheet.getColumns();
            for(int row = 0; row < rows; row++) {
                for(int col = 0; col < cols; col++) {
                    System.out.print(sheet.getCell(col, row).getContents()+" ");
                }
                System.out.println("\n");
            }
        } catch (IOException ex) {
            Logger.getLogger(Excel.class.getName()).log(Level.SEVERE, null, ex);
        } catch (BiffException ex) {
            Logger.getLogger(Excel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    
    //
    public static void exportData(String fileName, String tabName, String[][] data) throws FileNotFoundException, IOException {
        //Create new workbook and tab
        org.apache.poi.ss.usermodel.Workbook wb = new HSSFWorkbook();
        FileOutputStream fileOut = new FileOutputStream(fileName);
        org.apache.poi.ss.usermodel.Sheet sheet = wb.createSheet(tabName);

        //Create 2D Cell Array
        Row[] row = new Row[data.length];
        Cell[][] cell = new Cell[row.length][];

        //Define and Assign Cell Data from Given
        for (int i = 0; i < row.length; i++) {
            row[i] = sheet.createRow(i);
            cell[i] = new Cell[data[i].length];

            for (int j = 0; j < cell[i].length; j++) {
                cell[i][j] = row[i].createCell(j);
                cell[i][j].setCellValue(data[i][j]);
            }
        }
        //Export Data
        wb.write(fileOut);
        fileOut.close();
    }
}
